package servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.ArrayList;

import save.MyTools; 

@WebServlet("/AddGoodsServlet")
public class AddGoodsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        // 获取表单数据
        String name = request.getParameter("name");
        float price = Float.parseFloat(request.getParameter("price"));
        int num = Integer.parseInt(request.getParameter("num"));

        // 获取上传的图片
        Part filePart = request.getPart("image"); // 处理multipart/form-data
        String fileName = getSubmittedFileName(filePart);
        String directory = "D:\\temp\\images"; // 需要设置为应用的动态img目录
        File file = new File(directory, fileName);
        saveFile(filePart, file);

        // 创建GoodsSingle对象
        GoodsSingle single = new GoodsSingle();
        single.setName(name);
        single.setPrice(price);
        single.setNum(num);
        single.setImgename(fileName); // 设置图片文件名

        // 添加商品到文本文件
        MyTools.appendGoods_txt(single);

        // 加载更新后的商品列表
        ArrayList<GoodsSingle> goodslist = MyTools.loadGoods_txt();
        getServletContext().setAttribute("goodslist", goodslist);

        // 转发到show.jsp
        request.getRequestDispatcher("/show.jsp").forward(request, response);
    }

    private String getSubmittedFileName(Part part) {
        String fileName = null;
        String cd = part.getHeader("Content-Disposition");
        if (cd != null && !cd.isEmpty()) {
            String[] items = cd.split(";");
            for (String item : items) {
                if (item.trim().startsWith("filename")) {
                    fileName = item.trim().split("=")[1].replace("\"", "");
                    break;
                }
            }
        }
        return fileName;
    }

    private void saveFile(Part part, File file) throws IOException {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = part.getInputStream();
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
}